#_*_coding:utf-8_*_
from bs4 import  BeautifulSoup
import urlparse
import re
from py2neo import Graph,Node,Relationship,NodeSelector,Subgraph
import time
graph = Graph(password = "admin")
class HtmlPsrser(object):

    def _get_new_urls(self, page_url, soup):
        new_urls = set()
        # links = soup.find_all('a', href=re.compile(r"/item/\d+\.html"))
        links = soup.find_all('a', href=re.compile(r"/item/(.*)"))
        for link in links:
            new_url = link['href']
            new_full_url = urlparse.urljoin(page_url, new_url)
            new_urls.add(new_full_url)
        return new_urls

    def _get_new_data(self, page_url, soup):
        res_data = {}

        res_data['url'] = page_url

        #<dd class="lemmaWgt-lemmaTitle-title"><h1>Python</h1>
        title_node = soup.find('dd', class_="lemmaWgt-lemmaTitle-title").find("h1")
        res_data['title'] = title_node.get_text()
        print res_data['title']
        #<div class="lemma-summary" label-module="lemmaSummary">
        summary_node = soup.find('div', class_="lemma-summary")
        # res_data['summary'] = summary_node.get_text()
        #简介
        nodelist=[]
        list=[]
        try:
            res_data['summary'] = summary_node.contents[1].text
            imgsrc = soup.find('div', class_="summary-pic").find('img')['src']
            print res_data['summary']
        except:
            res_data['summary'] = summary_node.get_text()
            imgsrc= ''
        nodelist.append({'name':res_data['title'],'src':imgsrc})

        #featureBaseInfo
        works_node = soup.find('div', class_="star-info-block works")
        worksname=works_node.find("dt").get_text()
        worklist=[]
        for work in works_node.find('ul').contents:
            try:
                print res_data['title'],worksname, work.get_text().replace("\n", ""),work.find('img')['src']
                worklist.append({'title':res_data['title'],'rel':worksname,'work':work.get_text().replace("\n", ""),'src':work.find('img')['src']})
                nodelist.append({'name': work.get_text().replace("\n", ""), 'src': work.find('img')['src']})
                rel = Relationship(Node("baidu", name=res_data['title'], src=imgsrc), "baidu_link",
                                   Node("baidu", name=work.get_text().replace("\n", ""),src=work.find('img')['src']),
                                   name=worksname,)
                list.append(rel)
            except:
                print 'skip'
                # a=1+1
        # res_data['work'] =worklist
        # star-info-block relations
        try:
            relations_node = soup.find('div', class_="star-info-block relations")
            relationsname=relations_node.find("dt").get_text()
            for relation in relations_node.find('ul').contents:
                try:
                    print res_data['title'],relationsname,relation.find('em').previousSibling, relation.find('em').get_text().replace("\n", ""),relation.find('img')['src']
                    worklist.append({'title': res_data['title'],'rel':relation.find('em').previousSibling, 'work': relation.find('em').get_text().replace("\n", ""),'src': relation.find('img')['src']})
                    nodelist.append({'name': relation.find('em').get_text().replace("\n", ""), 'src': relation.find('img')['src']})
                    rel = Relationship(Node("baidu", name=res_data['title'], src=imgsrc), "baidu_link",
                                   Node("baidu", name=relation.find('em').get_text().replace("\n", ""), src=relation.find('img')['src']),
                                   name=relation.find('em').previousSibling)
                    list.append(rel)
                except:
                    print 'skip'
                    # a = 1 + 1
        except:
            print '无好友关系'
        # basicinfo_node = soup.find('div', class_="basic-info cmn-clearfix")
        # basicinfoname= soup.find('span', class_="headline-content").get_text()
        #
        # for index, basicinfo in enumerate(basicinfo_node.find('dl').contents):
        #     try:
        #         print index
        #         print res_data['title'],basicinfoname,basicinfo.get_text().replace("\n", "")
        #
        #     except:
        #         print 'skip'

        # links = soup.find_all('a', href=re.compile(r"/item/(.*)"))
        # basicinfo_node = soup.find('div', class_="starMovieAndTvplay")
        # basicinfoname = soup.find('h3', class_="headline-content").get_text()
        # for basicinfo in basicinfo_node.find('dl').contents:
        #     try:
        #         print res_data['title'], basicinfoname, basicinfo.get_text().replace("\n", "")
        #     except:
        #         print 'skip'
        # print worklist
        # print nodelist


        A=Subgraph(relationships=list)
        graph.merge(A,None,('name'))
        return res_data

    def parse(self, page_url, html_cont):
        if page_url is None or html_cont is None:
            return

        soup = BeautifulSoup(html_cont, 'html.parser', from_encoding='utf-8')
        new_urls = self._get_new_urls(page_url, soup)
        new_data = self._get_new_data(page_url, soup)
        return  new_urls, new_data